package cac.common.CallInterFace.rest;

import java.text.ParseException;
import java.util.*;

import cac.common.CallInterFace.service.CallInterfaceService;
import cac.common.CreatMsgId;
import cac.gkinterface.service.WorkService;
import com.alibaba.fastjson.JSONArray;
import com.cac.dme.adapter.rest.msg.ResponseMsg;

import com.cac.dme.adapter.utils.ComUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/sendMaterialInterface")
@Component
public class SendMaterialInterface {


    @Autowired
    private CallInterfaceService callInterfaceService;
    @Autowired
    private Environment environment;
    @Autowired
    private WorkService workService;


    /**
     * @title: 101-MES发送文件
     * @description:
     * paramMap.put("dmsCode", "ms_gzbps");
     * paramMap.put("delivery_plan_code", groupCode);网闸查询数据SQL所需条件
     * interfaceMap.put("code", "getMatchData");
     * interfaceMap.put("name", "获取数据配套场景的配套数据");
     * interfaceMap.put("parameters", paramMap);
     * interfaceMap.put("func", environment.getProperty("dispatch.func"));//发送文件所需func
     * interfaceMap.put("sendScenario", "物料配送");业务应用场景名称
     */

    @PostMapping("/sendMaterialInterface")
    public HashMap SendFileInterface(@RequestBody Map map) {
        HashMap responseMsg = new HashMap();
        if("true".equals(environment.getProperty("pathProperty.debug"))){
            responseMsg.put("retCode","200");
            return responseMsg;
        }
        System.out.println("map:" + map);
        //调用网闸数据打包功能接口
        /* 数据打包所需参数
        "code", "getMatchData"
        "name", "获取数据配套场景的配套数据"
        "dmsCode", 网闸场景编码
         */
        long flag = System.currentTimeMillis();
        map.put("flag",flag);
        try {
            HashMap result = callInterfaceService.getMatchData(map);
            if (result.get("retCode").equals("200")) {
                //获取网闸返回文件名以及文件路径
                result.get("result");
                String fileName = (String) result.get("fileName");
                String httpPath = (String) result.get("filePath");
                System.out.println("fileName>>>>>>>>>>>>>>>>>>>:" + fileName + "ooo>>>>>httpPath:" + httpPath);
                //json对象初始化
                JSONObject tmp = new JSONObject();
                JSONArray files = new JSONArray();
                JSONObject file = new JSONObject();
                file.put("fileName", fileName);
                file.put("httpPath", httpPath);
                files.add(file);
                //调用网闸sendFile所需参数组装
                String url = environment.getProperty("pathProperty.url");
                String msgId = CreatMsgId.getMsgId();
                //parameters
                tmp.put("files", files);
                tmp.put("url", url);
                tmp.put("sendSys", "分拣系统");
                tmp.put("targetSys", "MES系统");
                //获取传入场景名称
                tmp.put("sendScenario", map.get("sendScenario"));
                tmp.put("msgId", msgId);
                JSONObject funcJson = new JSONObject();
                funcJson.put("func", map.get("func"));
                String funcStr = funcJson.toJSONString();
                final Base64.Encoder encoder = Base64.getEncoder();
                String Data = encoder.encodeToString(funcStr.getBytes());
                tmp.put("BData", Data);
                System.out.println("==========工控网上传_" + map.get("sendScenario").toString() + "========================");
                //工控网上传数据
                HashMap issuedTest = new HashMap();
                issuedTest.put("id", ComUtil.getId());
                issuedTest.put("BData","打包文件返回值："+ result.toString());
                issuedTest.put("type", map.get("func"));
                issuedTest.put("msgId", msgId);
                try {
                    issuedTest.put("nowTime", cac.common.DateUtil.nowTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                System.out.println("工控网上传程序后台日志:>>>>>>>>>>>>issuedParameters:" + issuedTest.toString());
                System.out.println("=============工控网上传_" + map.get("sendScenario").toString() + "====================");

                System.out.println(">>>>>>>>>tmp:" + tmp);
                String parameters = tmp.toJSONString();
                System.out.println(">>>>>>>>>>>>>>parameters:" + parameters);
                long beginTime = System.currentTimeMillis();
                System.out.println("======开始时间=======" + beginTime);
                //调用网闸发送文件接口
                /* 数据打包所需参数
                  "code", "sendFile"
                  "name", "两网传输-发送文件"
                  "parameters", {"files":文件路径及文件名,"url":文件目的地链接地址,
                  "sendSys":发送系统,"targetSys":接收系统,"sendScenario":应用场景名}
               */
                HashMap result2 = callInterfaceService.sendFile("sendFile", "两网传输-发送文件", parameters);

                long endTime = System.currentTimeMillis();
                issuedTest.put("BData",issuedTest.get("BData")+"====配送传递文件返回值："+result2.toString());
                //写入erp接口日志
                workService.issuedTest(issuedTest);
                System.out.println("====配送==消耗时间=======" + (endTime - beginTime) + "ms");

                if (result2.get("retCode").equals("200")) {
                    responseMsg.put("retCode","200");
                    responseMsg.put("message","文件发送成功");
                    return responseMsg;
                }else {
                    responseMsg.put("retCode","201");
                    responseMsg.put("message","网闸发送文件失败");
                    return responseMsg;
                }
            } else {
                responseMsg.put("retCode","201");
                responseMsg.put("message","网闸打包数据失败");
                return responseMsg;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
            responseMsg.put("retCode","201");
            responseMsg.put("message",e.getMessage());
        } finally {
            return responseMsg;
        }
    }
}
